const path = require("path");
//创建WebSocket服务端的对象
const WebSocket = require("ws");

const fileUtils = require("../utils/file_utils");
//绑定端口号
const wss = new WebSocket.Server({
    port: 9998
})

module.exports.listen = () => {
    //对客户端的连接事件进行监听
    wss.on("connection", client => {
        console.log("有客户端连接成功了.......");
        //对客户端的连接对象message事件进行监听
        client.on("message", async (msg) => {
            console.log("客户端发送数据给服务端了" + msg);
            let payload = JSON.parse(msg);
            const action = payload.action;
            if (action == "getData") {
                let filePath = "../data/" + payload.chartName + ".json";
                filePath = path.join(__dirname, filePath);
                //读取文件内容
                const ret = await fileUtils.getFileJsonData(filePath);
                //需要在服务端获取到数据之前,增加一个字段data(某个json文件的内容)
                payload.data = ret;
                client.send(JSON.stringify(payload));
            } else {
                //原封不动转发给每一个处于连接状态的客户端
                // wss.clients:所有客户端的连接
                wss.clients.forEach(client => {
                    client.send(msg);
                })
            }
            //由服务端给客户端发送数据
            // client.send("返回的数据");
        })
    })
}
